﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Sl.Duplex {
	public class ComPortDesc {
		public readonly string id;
		public string info;
		public bool avaliable;
		protected string warning = string.Empty;
		public void addWarning(string w) {
			if (!string.IsNullOrEmpty(warning)) {
				warning += "/";
			}
			warning += w;
		}
		public ComPortDesc(string id) {
			this.id = id;
		}
		override public string ToString() {
			if (avaliable) {
				return $"✔{id}-{info}";
			} else {
				return $"【{warning}】{id}-{info}";
			}
		}
	}
	public class SerialPortScaner: IEnumerable<ComPortDesc>{
		public IEnumerable<ComPortDesc> Port_enum;
		public ComPortDesc[] Ports => Port_enum.OrderBy(cpd => !cpd.avaliable).ToArray();
		public int Avaliable_port_num => Ports.Count(cpd => cpd.avaliable);

		public SerialPortScaner() {
			Port_enum = (from str in System.IO.Ports.SerialPort.GetPortNames()
						select new ComPortDesc(str)).ToArray();
		}

		public IEnumerator<ComPortDesc> GetEnumerator() {
			return Port_enum.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator() {
			return ((IEnumerable)Port_enum).GetEnumerator();
		}
	}
}
